window.onload=function(){
    var agent = navigator.userAgent.toLowerCase() ;

    var regStr_ie = /msie [\d.]+;/gi ;
    if(agent.indexOf("msie") > 0)
    {
        if((agent.match(regStr_ie)+"").replace(/[^0-9.]/ig,"")<9){
            window.location.href = "erro/ieVup.html";
        };
    }
}
function uploadimg(obj){
    var objDefault = {
        id : "",
        title : "上传图片",
        btnTitle : "添加图片",
        url : 'http://localhost:8080/file/uploadfile',
        fileType: [
            "image/jpeg",
            "image/png",
            "image/gif"
        ],
        fileSize: 1024,
        maxFile : 5,
        minFile : 1,
        successFun : function(){},
        isFinish : function(){}
    };
    objDefault = $.extend(objDefault,obj);
    var initModal = function(){
        var files = [];
        var modal = $('<div></div>').addClass("modal fade").appendTo("body"),
            modal_dialog = $('<div></div>').addClass("modal-dialog").appendTo(modal),
            modal_content = $('<div></div>').addClass("modal-content").appendTo(modal_dialog),
            modal_header = $('<div></div>').addClass("modal-header").appendTo(modal_content),
            modal_body = $('<div></div>').addClass("modal-body").appendTo(modal_content),
            modal_footer = $('<div></div>').addClass("modal-footer").appendTo(modal_content),
            modal_close = $('<button data-dismiss="modal" aria-label="Close"></button>').addClass("close").appendTo(modal_header).append("<span>&times</span>"),
            modal_title = $('<h4></h4>').addClass("modal-title").text(objDefault.title).appendTo(modal_header),
            modal_erro = $('<span></span>').addClass("modal-erro").appendTo(modal_title),
            modal_progress = $('<div></div>').addClass("progress").appendTo(modal_body),
            modal_progress_bar = $('<div></div>').addClass("progress-bar progress-bar-striped active").appendTo(modal_progress),
            modal_progress_num = $('<span></span>').appendTo(modal_progress_bar),
            modal_imgbox =  $('<div></div>').addClass("img-box").appendTo(modal_body),
            modal_imglist = $('<div></div>').addClass("imgList").appendTo(modal_imgbox),
            modal_addimg = $('<label></label>').addClass("add-img").appendTo(modal_imgbox).text(objDefault.btnTitle),
            modal_fileinput = $('<input multiple="multiple" accept="image/jpeg,image/png,image/gif" type="file"/>').appendTo(modal_addimg),
            modal_cancel = $('<button data-dismiss="modal"></button>').addClass("btn btn-default").text("完成").appendTo(modal_footer),
            modal_upload = $('<button></button>').addClass("btn btn-primary").text("开始上传").prop("disabled",true).appendTo(modal_footer),
            modal_stop = $('<button></button>').addClass("btn btn-warning").text("停止上传").prop("disabled",true).appendTo(modal_footer);
            modal.modal('show');
        modal.on("hidden.bs.modal",function(){
            $(this).remove();
        });
        modal_fileinput.on("change",function(){
            btnDisable(0,1);
            modal_progress_bar.addClass("progress-bar-striped").removeClass("progress-bar-success").css({width: 0});
            $.each(this.files,function(i,v){
                files.push({"file":v});
                viewFile(v);
            });
            upCheck();
        });
        var viewFile = function(file) {
            var reader = new FileReader();
            reader.onload = function( e ){
                var imgBox = $("<div></div>").addClass("imgBox").appendTo(modal_imglist),
                    img = $("<img src='"+e.target.result+"'/>").appendTo(imgBox),
                    delImg = $("<div></div>").addClass("delImg").appendTo(imgBox).append('<span class="glyphicon glyphicon-remove"></span>');
                imgBox.click(function(){
                    $(this).remove();
                    files.splice($(this).index(),1);
                    upCheck();
                });
            }
            reader.readAsDataURL(file);
        }
        modal_upload.on("click",function(){upload()});
        var upload = function(){
            var xhr = new XMLHttpRequest(),
            fd = new FormData();
            $.each(files,function(i,v){
                fd.append("file"+i,files[i].file)
            })
            //监听状态，实时响应
            //xhr 和 xhr.upload 都有progress事件，xhr.progress是下载进度，xhr.upload.progress是上传进度
            xhr.upload.onprogress = function(event){
                if(event.lengthComputable){
                    var percent =Math.floor(event.loaded*100 / event.total);
                    console.log(percent+"%");
                    modal_progress_num.text(percent+"%");
                    modal_progress_bar.css({
                        width: percent+"%"
                    });
                }
                objDefault.isFinish()
            }

            //传输开始事件
            xhr.onloadstart = function(event){
                console.log("load start");
                modal_progress_num.text("正在上传");
                btnDisable(1,0);
                modal_stop.one('click',function(){
                    xhr.abort();
                    btnDisable(0,1);
                    modal_upload.text("重新开始");
                });
            }

            //ajax过程成功完成事件
            xhr.onload = function(event){
                console.log("load success");
                modal_progress_num.text("上传成功");
                modal_progress_bar.addClass("progress-bar-success");
                var ret = eval(xhr.responseText);
                //objDefault.successFun();
                objDefault.success(ret);
            }

            //ajax 过程发生错误事件
            xhr.onerror = function(event){
                modal_progress_num.text("发生错误");
				debugger;
                btnDisable(1,0);
                objDefault.error();
            }

            //ajax 被取消
            xhr.onabort = function (event) {
                console.log('abort');
                modal_progress_num.text("停止上传");
            }

            //loadend传输结束，不管成功失败都会被触发
            xhr.onloadend = function(event){
                btnDisable(1,1);
                console.log(xhr.responseText);
                console.log("load end");
            }

            //发起ajax请求传输数据
            xhr.open('POST',objDefault.url,true);
            xhr.send(fd);
        }
        var upCheck = function(){
            btnDisable(0,1);
            printErro("");
            if(files.length>= objDefault.maxFile){
                modal_addimg.hide();
                if(files.length>objDefault.maxFile){
                    printErro("(对不起，最多只能上传"+objDefault.maxFile+"个文件)");
                    btnDisable(1,1);
                }
            }else{
                modal_addimg.show();
            }
            $.each(files,function(i,v){
                if(objDefault.fileType.indexOf(v.file.type)<0){
                    printErro("(对不起，只能上传"+ $.each(objDefault.fileType,function(i,v){return v+" "})+"格式的文件哦)")
                    btnDisable(1,1);
                }
                if(objDefault.fileSize*1024<v.file.size){
                    printErro("(对不起，单个文件不能大于"+objDefault.fileSize+"kb)")
                    btnDisable(1,1);
                }
            });
        }
        var printErro = function(str){
            modal_erro.text(str);
        }
        var btnDisable = function(b,s){
            modal_upload.prop("disabled",b);
            modal_stop.prop("disabled",s);
        }
    }
    $("#"+objDefault.id).on("click",function(){initModal()});
}